package it.pir.es02ChatTCP;

import java.io.*;
import java.net.*;

public class ClientBin extends Client {

	private DataOutputStream dataOutputStream;
	
	public ClientBin(String nickname, String address, int port)	throws UnknownHostException, IOException {
		super(nickname, address, port);
	}

	@Override
	protected void connect() throws IOException {
		socket = new Socket(address, port);
		dataOutputStream = new DataOutputStream(socket.getOutputStream());
		Message authentication = new Message(nickname, "", Message.AUTHENTICATION);
		sendMessage(authentication);
	}

	@Override
	public void sendMessage(Message message) throws IOException {
		dataOutputStream.writeUTF(message.getNickname());
		dataOutputStream.writeUTF(message.getMessage());
		dataOutputStream.writeInt(message.getType());
		dataOutputStream.flush();
	}

	@Override
	public void run() {
		DataInputStream dataInputStream;
		try {
			dataInputStream = new DataInputStream(socket.getInputStream());
			while(true) {
				String nick = dataInputStream.readUTF();
				String msg = dataInputStream.readUTF();
				dataInputStream.readInt();
				System.out.println(nick + ": "+ msg);
			}
		} catch (IOException e) {
			System.out.println("ERRORE! Problemi di comunicazione con il server!");
			// Il programma termina perché il nome utente è già in uso
			System.exit(1);
		}
	}

}
